package com.nmbaiyun.yangrong.uhfg;

import android.os.Handler;
import android.util.Log;

import com.handheld.uhfr.UHFRManager;
import com.uhf.api.cls.Reader;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.pda.serialport.Tools;

// 单例模式，确保不多次初始化manager
public class UHFGUtil {
    private static UHFGUtil instance = new UHFGUtil();
    //获取唯一可用的对象
    public static UHFGUtil getInstance(){
        return instance;
    }
    private UHFGUtil(){
        initManager();
    }

    public UHFRManager manager;//uhf

    public void initManager(){
        if(manager == null){
            manager = UHFRManager.getInstance();
        }else{
            Log.e("UHFRUntil","UHFRManager 已经被初始化了！");
        }
    }

    public void close(){
        manager.close();
    }

    //    3次汇总统计
    public void count(UHFGUtilListenner listenner, int delys){
        Log.e("UHFRUntil","开始计数");

        if (delys == 0){
            delys = 1000;
        }
        int times = 0;
        Set<String> allDevices = new HashSet<String>();
        while (times <3){
            times +=1;
            manager.asyncStartReading();
            try {
                int finalTimes = times;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                    tagInventoryByTimer
                        List<Reader.TAGINFO> list = manager.tagInventoryRealTime();
//                    Log.i("scan", list.size()+"__"+list1.size()+"__"+list2.size());

                        manager.asyncStopReading();
                        if(list.size()>0){
                            Log.i("scan", list.get(0).toString());

                            for (Reader.TAGINFO tfs : list) {
                                byte[] epcdata = tfs.EpcId;

                                String data = Tools.Bytes2HexString(epcdata, epcdata.length);
                                allDevices.add(data);
//                        int rssi = tfs.RSSI;
//                        Message msg = new Message();
//                        msg.what = 1;
//                        Bundle b = new Bundle();
//                        b.putString("data", data);
//                        b.putString("rssi", rssi + "");
//                        msg.setData(b);
//
//                        datas += k + ".设备数据是："+data+"  "+rssi+"\r\n";
//                        k++;

                            }

                        }
                        if (finalTimes >= 3 && listenner != null){
                            listenner.callBackResult(allDevices.size(),allDevices);
                        }

                    }
                },delys);
            }catch (Exception e){
                manager.asyncStopReading();


            }

        }


    }

    //    获取一组耳标
    public void getRFIDs(UHFGUtilListenner listenner){
        manager.asyncStartReading();
        Set<String> allDevices = new HashSet<String>();
        try {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    tagInventoryByTimer
                    List<Reader.TAGINFO> list = manager.tagInventoryRealTime();
//                    Log.i("scan", list.size()+"__"+list1.size()+"__"+list2.size());

                    manager.asyncStopReading();
                    if(list.size()>0){
                        Log.i("scan", list.get(0).toString());

                        for (Reader.TAGINFO tfs : list) {
                            byte[] epcdata = tfs.EpcId;

                            String data = Tools.Bytes2HexString(epcdata, epcdata.length);
                            allDevices.add(data);
//                        int rssi = tfs.RSSI;
//                        Message msg = new Message();
//                        msg.what = 1;
//                        Bundle b = new Bundle();
//                        b.putString("data", data);
//                        b.putString("rssi", rssi + "");
//                        msg.setData(b);
//
//                        datas += k + ".设备数据是："+data+"  "+rssi+"\r\n";
//                        k++;

                        }

                    }
                    if ( listenner != null){
                        listenner.callBackResult(allDevices.size(),allDevices);
                    }

                }
            },500);
        }catch (Exception e){
            manager.asyncStopReading();
        }
    }

    /**
     * 同步，返回1个设备
     * @return
     * @throws InterruptedException
     */
    public String getSyncRFID() {
        String data = "";
        try{
            manager.asyncStartReading();
//            Thread.sleep(300);
            List<Reader.TAGINFO> list = manager.tagInventoryRealTime();
            if(list.size()>0) {
                Log.i("getSyncRFID", list.get(0).toString());

                for (Reader.TAGINFO tfs : list) {
                    byte[] epcdata = tfs.EpcId;

                    data = Tools.Bytes2HexString(epcdata, epcdata.length);

                }
            }
            manager.asyncStopReading();
            return data;
        }catch (Exception e){
            Log.e("getSyncRFID",e.getMessage());
            return data;
        }
    }

    /**
     * realTime是实时的，需要配合asyncStartReading使用，读到多少标签就返回多少标签，适合大批量成百上千个标签盘点的时候；定时的是单独的，不需要在asyncStartReading之后使用，是在输入的一定时间内的标签，适合标签数较少，比如几十个的时候
     *
     * 同步，返回一组设备
     * @return
     */
    public Set<String> getSyncRFIDList(){
        Set<String> allDevices = new HashSet<String>();
        try{
            manager.asyncStartReading();
//            Thread.sleep(300);
            List<Reader.TAGINFO> list = manager.tagInventoryRealTime();
            if(list.size()>0) {
                Log.i("getSyncRFID", list.get(0).toString());

                for (Reader.TAGINFO tfs : list) {
                    byte[] epcdata = tfs.EpcId;

                    String data = Tools.Bytes2HexString(epcdata, epcdata.length);
                    allDevices.add(data);
                }
            }
            manager.asyncStopReading();
            return allDevices;
        }catch (Exception e){
            Log.e("getSyncRFID",e.getMessage());
            return allDevices;
        }

    }



//    获取设备读写功率

    /**
     * 获取设备读写功率,功率越大越费电，可监测范围越远
     * @return
     */
    public String getPower(){
        int [] result = manager.getPower();
        if(result != null){
            return "读功率："+result[0]+" 写功率："+result[1];
        }
        return "获取失败";
    }

    /**
     * 设置设备读写功率
     * @param readPower 5~30
     * @param writePower 5~30
     * @return
     */
    public Boolean setPower(int readPower, int writePower){
        Reader.READER_ERR err = manager.setPower(readPower,writePower);
        return err == Reader.READER_ERR.MT_OK_ERR;

    }


}


